package main.java.indi.zyj.coderecord;

import main.java.indi.zyj.hot100.base.TreeNode;

public class ConstructMaximumBinaryTree {

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return constructMaximumBinaryTree1(nums, 0, nums.length - 1);
    }

    private TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) {

        if (rightIndex - leftIndex < 0) {// 没有元素了
            return null;
        }
        if (rightIndex - leftIndex == 0) {// 只有一个元素
            return new TreeNode(nums[leftIndex]);
        }
        int maxIndex = leftIndex;// 最大值所在位置
        int maxVal = nums[maxIndex];// 最大值
        for (int i = leftIndex; i <= rightIndex; i++) {
            if (nums[i] > maxVal){
                maxVal = nums[i];
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(maxVal);
        // 根据maxIndex划分左右子树
        root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex - 1);
        root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex);
        return root;

    }

}
